package com.zoroki.hmusic.controller;
import com.google.gson.*;
import com.zoroki.hmusic.constant.MessageConstant;
import com.zoroki.hmusic.entity.User;
import com.zoroki.hmusic.service.IUserService;
import com.zoroki.hmusic.entity.Result;
import com.zoroki.hmusic.util.BCryptUtil;
import com.zoroki.hmusic.util.GsonUtil;
import com.zoroki.hmusic.util.QiniuUtil;
import com.zoroki.hmusic.util.VerificationCodeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@RestController
@RequestMapping("/user")
@CrossOrigin("*")
@Slf4j
@Tag(name = "用户")
public class UserController {
    @Autowired
    IUserService userService;

    @Operation(summary = "根据用户id查找用户")
    @GetMapping("/findUserById")
    @ResponseBody
    public Result findUserById(@RequestParam Integer id) {
        User user = userService.findUserByColumn("id", id);
        if (user != null) {
            //如果相同，说明是本人
            return new Result(true, MessageConstant.USER_SEARCH_SUCCESS, user);
        }
        return new Result(false, MessageConstant.USER_SEARCH_FAILURE, null);

    }
    @Operation(summary = "使用email和password来登录")
    @GetMapping("/login")
    @ResponseBody
    public Result login(@RequestParam String email, @RequestParam String password) {
        //根据email查询用户
        User user = userService.findUserByColumn("email", email);
        if (user != null) {
            //将前端传来的密码与数据库中加密的密码进行对比
            boolean isSame = BCryptUtil.checkPassword(password, user.getPassword());
            //对比完密码后别忘了把密码清空
            user.setPassword(null);
            if (isSame) {
                //如果相同，说明是本人
                log.info("\"{}\" 登录...", "id:" + user.getId() + " username:" + user.getUsername());
                return new Result(true, MessageConstant.LOGIN_USER_SUCCESS, user);
            }
        }
        return new Result(false, MessageConstant.LOGIN_USER_FAILURE, null);
    }
    @Operation(summary = "传入一个user来进行注册")
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        /** TODO 注册规则
         *  1.邮箱不能相同
         *  2.用户名可以重复
         *  3.手机号不能相同，但可以不填
         *  4.头像的地址必须填写（能到这里头像都是有地址的
         */
        //1.查询邮箱是否有相同 (在之前验证过了所以不用验证
        //2.直接将数据插入到数据库
        int i = userService.addUser(user);
        if (i > 0) {
            return new Result(true, MessageConstant.USER_ADD_SUCCESS, null);
        } else {
            return new Result(false, MessageConstant.USER_ADD_FAILURE, null);
        }
    }
    @Operation(summary = "输入email来检测邮箱是否存在")
    @PostMapping("/checkEmail")
    @ResponseBody
    public Result checkEmail(@RequestBody String email) {
        String parser = GsonUtil.jsonParser(email, "email");
        User user = userService.findUserByColumn("email", parser);
        if (user != null) {
            //存在，不允许注册
            return new Result(false, MessageConstant.USER_EXIST, MessageConstant.NO);
        }
        //不存在，可以注册
        return new Result(true, MessageConstant.USER_NOT_EXIST, MessageConstant.YES);
    }
    @Operation(summary = "获取七牛云的upToken")
    @GetMapping("/upToken")
    @ResponseBody
    public Result upToken() {
        String upToken = QiniuUtil.getUpToken();
        return new Result(false, MessageConstant.LOGIN_USER_FAILURE, upToken);
    }

    @Operation(summary = "传入user来更新用户信息")
    @PutMapping("/updateUser")
    @ResponseBody
    public Result updateUser(@RequestBody User user) {
        int i = userService.updateUser(user);
        if (i > 0) {
            return new Result(true, MessageConstant.USER_UPDATE_SUCCESS, null);
        }
        return new Result(false, MessageConstant.USER_UPDATE_FAILURE, null);
    }
    @Operation(summary = "根据keyword来查询用户")
    @GetMapping("/findUserByKeyword")
    @ResponseBody
    public Result findUserByKeyword(@RequestParam String keyword) {
        SearchHits<User> users = userService.findUserByKeyword(keyword);
        if (users.getTotalHits() > 0) {
            return new Result(true, MessageConstant.USER_SEARCH_SUCCESS, users);
        }
        return new Result(false, MessageConstant.USER_SEARCH_FAILURE, null);
    }
    @Operation(summary = "根据keyword来分页查询用户")
    @GetMapping("/getUserPageByKeyword")
    @ResponseBody
    public Result getUserPageByKeyword(@RequestParam String keyword, @RequestParam int pageIndex) {
        Page<User> users = userService.getUserPageByKeyword(keyword, pageIndex);
        if (users.getTotalElements() > 0) {
            return new Result(true, MessageConstant.USER_SEARCH_SUCCESS, users);
        }
        return new Result(false, MessageConstant.USER_SEARCH_FAILURE, null);
    }
    @Operation(summary = "根据id来删除用户")
    @DeleteMapping("/deleteUserById")
    @ResponseBody
    public Result deleteUserById(@RequestParam int id) {
        int delete = userService.deleteUserById(id);
        if (delete > 0) {
            return new Result(true, MessageConstant.USER_DELETE_SUCCESS, null);
        }
        return new Result(false, MessageConstant.USER_DELETE_FAILURE, null);
    }

    @Operation(summary = "根据playlistId来查询用户")
    @GetMapping("/findUserByPlaylistId")
    @ResponseBody
    public Result findUserByPlaylistId(@RequestParam int playlistId) {
        User user = userService.findUserByPlaylistId(playlistId);
        if (user != null) {
            return new Result(true, MessageConstant.YES, user);
        }
        return new Result(false, MessageConstant.NO, null);
    }

    @PostMapping("/forgetPasswordCreateCodeByEmail")
    @ResponseBody
    public Result forgetPasswordCreateCodeByEmail(@RequestBody String email) {
        String parserEmail = GsonUtil.jsonParser(email, "email");

        String verificationCode = VerificationCodeUtil.getCode(4);

        //验证码保存格式为 code + email
        VerificationCodeUtil.setCode("code" + parserEmail, verificationCode);

        return new Result(true, MessageConstant.YES, null);
    }

    @PostMapping("/forgetPasswordCheckCode")
    @ResponseBody
    public Result forgetPasswordCheckCode(@RequestBody String requestBody) {
        boolean b = VerificationCodeUtil.checkCode(
                GsonUtil.jsonParser(requestBody, "email"),
                GsonUtil.jsonParser(requestBody, "code")
        );
        if (b) {
            return new Result(true, MessageConstant.YES, null);
        }
        return new Result(false, MessageConstant.NO, null);
    }

    @PostMapping("/editPasswordByEmail")
    @ResponseBody
    public Result editPasswordByEmail(@RequestBody String requestBody) {
        String email = GsonUtil.jsonParser(requestBody, "email");
        String password = GsonUtil.jsonParser(requestBody, "password");
        System.out.println(email + password);
        int i = userService.editPasswordByEmail(
                email,
                password
        );
        if (i > 0) {
            return new Result(true, MessageConstant.YES, null);
        }
        return new Result(false, MessageConstant.NO, null);
    }



}
